# result_frame.py
import cv2
import numpy as np
from PyQt5.QtWidgets import QFrame, QLabel
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import Qt, QTimer


class ResultFrame(QFrame):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setStyleSheet("background-color: white; border: 2px solid white;")
        self.setFixedSize(1000, 660)
        self.setGeometry(480, 100, 1000, 660)

        # 创建一个标签来显示图片
        self.result_label = QLabel(self)
        self.result_label.setGeometry(0, 0, 1000, 660)  # 设置标签大小
        self.result_label.setAlignment(Qt.AlignCenter)

    def display_results(self, im0):
        """
        接收检测结果（im0）并更新界面显示
        """
        if isinstance(im0, np.ndarray):
            # 将OpenCV图像（BGR格式）转换为QImage
            height, width, channel = im0.shape
            bytes_per_line = 3 * width
            q_image = QImage(im0.data, width, height, bytes_per_line, QImage.Format_BGR888)
            pixmap = QPixmap.fromImage(q_image)

            # 获取标签的当前大小
            label_width = self.result_label.width()
            label_height = self.result_label.height()

            # 调整图片大小，使其适应标签的大小，并保持宽高比
            scaled_pixmap = pixmap.scaled(label_width, label_height, Qt.KeepAspectRatio, Qt.SmoothTransformation)

            # self.result_label.setPixmap(pixmap)  # 显示图像
            # 设置缩放后的图片
            self.result_label.setPixmap(scaled_pixmap)
            self.result_label.repaint()  # 强制刷新

    def display_image_path_results(self, image_path):
        """接收图片或视频路径并在界面上显示图像或视频帧"""
        try:
            # 常见的视频扩展名，包括大写和小写
            video_extensions = ('.mp4', '.avi', '.mov', '.mkv', '.flv', '.webm', '.ts', '.3gp')

            # 将文件路径转换为小写，确保扩展名的大小写不影响判断
            if image_path.lower().endswith(video_extensions):  # 判断是否是视频文件
                cap = cv2.VideoCapture(image_path)
                if not cap.isOpened():
                    raise FileNotFoundError(f"无法加载视频：{image_path}")

                # 获取视频帧率（FPS）
                fps = cap.get(cv2.CAP_PROP_FPS)

                # 设置定时器，根据帧率读取并显示每一帧
                self.timer = QTimer()
                self.timer.timeout.connect(lambda: self.update_frame(cap))
                self.timer.start(int(1000 / fps))  # 每帧的时间间隔

            else:  # 处理图像文件
                # 使用OpenCV读取图像
                im0 = cv2.imread(image_path)
                if im0 is None:
                    raise FileNotFoundError(f"无法加载图像：{image_path}")

                # 将OpenCV图像（BGR格式）转换为RGB格式
                im0 = cv2.cvtColor(im0, cv2.COLOR_BGR2RGB)

                # 将OpenCV图像（RGB格式）转换为QImage
                height, width, channel = im0.shape
                bytes_per_line = 3 * width
                q_image = QImage(im0.data, width, height, bytes_per_line, QImage.Format_RGB888)
                pixmap = QPixmap.fromImage(q_image)

                # 获取标签的当前大小
                label_width = self.result_label.width()
                label_height = self.result_label.height()

                # 调整图片大小，使其适应标签的大小，并保持宽高比
                scaled_pixmap = pixmap.scaled(label_width, label_height, Qt.KeepAspectRatio, Qt.SmoothTransformation)

                # 设置缩放后的图片
                self.result_label.setPixmap(scaled_pixmap)
                self.result_label.repaint()  # 强制刷新

        except Exception as e:
            print(f"错误: {e}")

    def update_frame(self, cap):
        """从视频读取下一帧并更新显示"""
        ret, frame = cap.read()
        if not ret:  # 如果没有读取到帧（视频结束）
            cap.release()
            self.timer.stop()  # 停止定时器
            print("视频播放完毕！")
            return

        # 将BGR格式转换为RGB格式
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

        # 转换为QImage并显示
        height, width, channel = frame.shape
        bytes_per_line = 3 * width
        q_image = QImage(frame.data, width, height, bytes_per_line, QImage.Format_RGB888)
        pixmap = QPixmap.fromImage(q_image)

        label_width = self.result_label.width()
        label_height = self.result_label.height()
        scaled_pixmap = pixmap.scaled(label_width, label_height, Qt.KeepAspectRatio, Qt.SmoothTransformation)

        # 更新标签中的图片
        self.result_label.setPixmap(scaled_pixmap)
        self.result_label.repaint()  # 强制刷新
